package com.zjcode.oa.service.impl;

import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjcode.oa.config.MConsts;
import com.zjcode.oa.mapper.OaJournalAttachmentMapper;
import com.zjcode.oa.mapper.OaProjectJournalMapper;
import com.zjcode.oa.mapper.ZjcodeSysUserMapper;
import com.zjcode.oa.model.OaJournalAttachment;
import com.zjcode.oa.model.OaProjectJournal;
import com.zjcode.oa.model.ZjcodeSysUser;
import com.zjcode.oa.service.ProjectJournalService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName:ProjectJournalServiceImpl
 * @功能：
 * @author：wlei
 * @日期：2022/4/8-11:31 PM
 **/
@Service
public class ProjectJournalServiceImpl implements ProjectJournalService, BaseService {

    @Autowired
    private OaProjectJournalMapper projectJournalMapper;
    @Autowired
    private ZjcodeSysUserMapper sysUserMapper;
    @Autowired
    OaJournalAttachmentMapper journalAttachmentMapper;

    @Override
    public Map<String, Object> listByPage(PageData pageData) {
        String minRecordDatetime = (String) pageData.get("minRecordDatetime");
        String maxRecordDatetime = (String) pageData.get("maxRecordDatetime");
        String createBy = (String) pageData.get("createBy");
        String projectId = (String) pageData.get("projectId");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        MPage mPage = getPageInfo(pageData);
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
        List<LinkedHashMap<String, Object>> list = new ArrayList<>();
        try {
            list.addAll(projectJournalMapper.listByPage(
                minRecordDatetime != null ? sdf.parse(minRecordDatetime) : null,
                maxRecordDatetime != null ? sdf.parse(maxRecordDatetime) : null,
                createBy,
                projectId));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 解析附件
        parseAttachment(list);

        return PaginationBuilder.buildResult(list,
                                             page.getTotal(),
                                             mPage.getCurrentPage(),
                                             mPage.getPageSize());
    }


    @Override
    public int insert(OaProjectJournal record) {
        if (record != null) {
            return projectJournalMapper.insert(record);
        }
        return 0;
    }

    @Override
    public int insertList(List<OaProjectJournal> list) {
        return projectJournalMapper.insertList(list);
    }

    @Override
    public List<OaProjectJournal> selectAllJournalBy(Date minRecordDatetime,
                                                     Date maxRecordDatetime,
                                                     String createBy) {
        return projectJournalMapper.selectAllByRecordDatetimeBetweenOrEqualToAndCreateByOrderByCreateTime(
            minRecordDatetime,
            maxRecordDatetime,
            createBy);
    }

    @Override
    public int delById(String id) {
        OaProjectJournal journal = projectJournalMapper.selectByPrimaryKey(id);
        if (journal != null) {
            journal.setIsDelete(1);
            journal.setUpdateTime(new Date(System.currentTimeMillis()));
            return projectJournalMapper.updateByPrimaryKey(journal);
        } else {
            return -1;
        }

    }

    @Override
    public List<ZjcodeSysUser> selectAllDevelopers() {
        return sysUserMapper.selectAllDevelopers();
    }

    @Override
    public int insertAttachments(List<OaJournalAttachment> attachments) {
        if (attachments.size() > 0) {
            return journalAttachmentMapper.insertList(attachments);
        } else {
            return 0;
        }
    }


    /**
     * 解析出日志中的附件信息
     *
     * @param journals
     */
    private void parseAttachment(List<LinkedHashMap<String, Object>> journals) {
        journals
            .parallelStream()
            .forEach(each -> {
                String filenames = (String) each.get("filenames");
                String filepaths = (String) each.get("filepaths");
                String attachmentsids = (String) each.get("attachmentsids");
                // 对是否允许拆分进行判断
                if (attachmentsids != null) {
                    String[] ids = attachmentsids.split(MConsts.STRING_SEPARATOR);
                    String[] names = filenames.split(MConsts.STRING_SEPARATOR);
                    String[] paths = filepaths.split(MConsts.STRING_SEPARATOR);

                    List<String> list = Arrays.asList(ids);

                    AtomicInteger index = new AtomicInteger();
                    List<OaJournalAttachment> attachments = list
                        .stream()
                        .map(id -> {
                            OaJournalAttachment oaJournalAttachment = getJournalAttachment(names,
                                                                                           paths,
                                                                                           index,
                                                                                           id);
                            index.getAndIncrement();
                            return oaJournalAttachment;
                        })
                        .collect(Collectors.toList());

                    each.put("attachments", attachments);
                } else {
                    each.put("attachments", null);
                }
            });
    }

    /**
     * 获取附件对象
     *
     * @param names
     * @param paths
     * @param index
     * @param id
     * @return
     */
    private OaJournalAttachment getJournalAttachment(String[] names,
                                                     String[] paths,
                                                     AtomicInteger index,
                                                     String id) {
        OaJournalAttachment oaJournalAttachment = new OaJournalAttachment();
        oaJournalAttachment.setId(Integer.parseInt(id));
        oaJournalAttachment.setFileName(names[index.get()]);
        oaJournalAttachment.setFilePath(paths[index.get()]);
        return oaJournalAttachment;
    }
}
